package com.dlut.txy.designpattern.schedule.taskunit.impl;

import com.dlut.txy.designpattern.schedule.task.ScheduleTask;
import com.dlut.txy.designpattern.schedule.task.TaskStatus;
import com.dlut.txy.designpattern.schedule.taskunit.TaskUnit;
import lombok.EqualsAndHashCode;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * delayQueue.remove(delayQueueTaskUnit)，所以要重写equals
 * 而且因为delayQueue每一次取出任务执行，是把当前任务对象扔点，再重新放心的任务对象进去，所以前后不是一个taskUnit对象，
 * 把要这2个taskUnit对象不一样的字段忽略掉，让其equals相等
 */
@EqualsAndHashCode(exclude = {"expireTimestamp"})
public class DelayQueueTaskUnit extends TaskUnit implements Delayed {
    private long expireTimestamp;

    public DelayQueueTaskUnit(ScheduleTask scheduleTask, int scheduleMills) {
        super(scheduleTask, scheduleMills);
        this.expireTimestamp= System.currentTimeMillis() + scheduleMills;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return  unit.convert(this.expireTimestamp - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
